<template>
    <div>
        <h3>评论区</h3>
        <hr>
        <textarea placeholder="请输入要评论的内容(最多120字)" maxlength="120" v-model="comment"></textarea>
        <mt-button type="primary" size="large" @click="sendComment">发表评论</mt-button>
        <div class="cmt-list">
            <div class="cmt-item" v-for="(value,index) in comments" :key="index">
                <div class="cmt-title">
                    第{{index+1}}楼&nbsp;&nbsp;用户：{{value.name}}&nbsp;&nbsp;发表时间：{{value.time}}
                </div>
                <div class="cmt-body">
                    {{value.content}}
                </div>
            </div>
        </div>

        <mt-button type="danger" size="large" plain @click="moreComments">加载更多</mt-button>

    </div>
</template>

<script>
    import {Toast} from 'mint-ui'
    export default {
        name: "comment",
        data(){
            return {
                comments:[],
                comment:'',
            //    当前显示条数 （5为每页显示条数）
                nowLength:0,
            }
        },
        created(){
            this.getComments();
        },
        methods:{
            getComments(){
                this.$http.get('/api/comments').then(res=>{
                    //添加评论到页面中，
                    this.comments=this.comments.concat(res.body.data.slice(this.nowLength,(this.nowLength+5) > res.body.data.length ? res.body.data.length : (this.nowLength+5)));
                })
            },
            moreComments(){
                //每次点击更多添加5条
                this.nowLength+=5;
                this.getComments();
            },
            sendComment(){
                if(this.comment.trim()===''){
                    Toast('评论不能为空')
                }else{
                    this.$http.post('/api/comments',{name:'郭',time:this.getTime(),content:this.comment.trim()},{emulateJSON:true}).then(res=>{
                        if (res.status === 200) {
                            this.comments.unshift({name: '郭', time: this.getTime(), content: this.comment.trim()});
                            this.comment = '';
                        }
                        else {
                            Toast('发送评论失败')
                        }
                })}
            },
            getTime(){
                //时间处理函数
                var myDate=new Date()
                return myDate.toLocaleString('chinese', { hour12: false }).replace(/\//g,'-');
            }
        }
    }
</script>

<style lang="scss" scoped>
    textarea{
        font-size: 14px;
        height: 85px;
        margin: 0;
    }
    .cmt-list{
        .cmt-item{
            font-size: 13px;
            .cmt-title{
                line-height: 30px;
                background-color: #ccc;
            }
            .cmt-body{
                line-height: 35px;
                text-indent: 2em;
            }
        }
    }
</style>